<?php
/*
 *      access.class.php
 *      
 *      Copyright 2009 Valery Tverdohleb <tvsdesign@gmail.com>
 *      
 *      This program is free software; you can redistribute it and/or modify
 *      it under the terms of the GNU General Public License as published by
 *      the Free Software Foundation; either version 2 of the License, or
 *      (at your option) any later version.
 *      
 *      This program is distributed in the hope that it will be useful,
 *      but WITHOUT ANY WARRANTY; without even the implied warranty of
 *      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *      GNU General Public License for more details.
 *      
 *      You should have received a copy of the GNU General Public License
 *      along with this program; if not, write to the Free Software
 *      Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 *      MA 02110-1301, USA.
 */

class Access
{
    protected $signedin = false;
    protected $id;
    
    public function __construct()
    {
	session_name('ESID');
	if(array_key_exists(session_name(),$_COOKIE))
	{
	    session_start();
	    if(isset($_SESSION['signedin']) && ($_SESSION['signedin'] == 1))
	    {
		    $this->signedin = true;
		    $this->id = $_SESSION['id'];
	    }
	}
    }
    
    public function isSignedIn()
    {
	return $this->signedin;
    }
    
    public function getId()
    {
	return $this->id;
    }
    
    public function login($login, $password)
    {
	$stmt = Engine::get()->db->prepare('SELECT `id` FROM `users` WHERE `login` = :login AND `password` = :password LIMIT 1;');
	$stmt->bindValue(':login',$login);
	$stmt->bindValue(':password',md5($password));
	$stmt->execute();
	if ($stmt->rowCount() != 1) throw new Security_Exception(STR::WRONG_CREDENTIALS);
	$id = $stmt->fetchColumn();
	$this->signedin = true;
	$this->id = $id;
	$stmt = Engine::get()->db->prepare('UPDATE `users` SET `logged` = true WHERE `id` = :id LIMIT 1;');
	$stmt->bindValue(':id', $this->id);
	$stmt->execute();
	session_start();
	$_SESSION['signedin'] = 1;
	$_SESSION['id'] = $id;
	Engine::get()->constructPlayer($id);
    }
    
    public function logout()
    {
	$_SESSION['signedin'] = false;
	$_SESSION['id'] = 0;
	@session_destroy();
	setcookie('ESID',0,1);
	$stmt = Engine::get()->db->prepare('UPDATE `users` SET `logged` = false WHERE `id` = :id LIMIT 1;');
	$stmt->bindValue(':id', $this->id);
	$stmt->execute();
	$this->signedin = false;
	$this->id = null;
    }
   
    
}

?>
